﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Windows.Forms;
using LEDControllerTools.Commands;
using LEDControllerTools.Controller;
using LEDControllerTools.Scripting;
using LedController.Properties;

namespace LedController
{

	static class Program {


        //Create the model (controller) from the congiguration
	    private static ICommandFactory commandFactory = Settings.Default.Controller;
        static IControllable controllable = Controller.GetInstance(commandFactory);

		/// <summary>
		/// The main entry point for the application.
		/// </summary>
		[STAThread]
        static void Main(string[] args)
        {
            
            //Create the view
			Application.EnableVisualStyles();
			Application.SetCompatibleTextRenderingDefault(false);
            var view = new frmLedPanelView();
            //var view = new Form1();

            //Configure controller events
            controllable.PinToggled += view.Controller_PinToggled;
		    controllable.BatteryUpdate += view.Controller_BatteryUpdate;
            controllable.StatusUpdate += controllable_StatusUpdate;

            //Configure view events
            view.IssueDigitalCommand += view_IssueCommand;
            view.RequestBattery += view_RequestBattery;
            
            //Run a demo script
            if (args.Length > 0)
            {
                var engine = RunLines(args[0], controllable);
                //ScriptEngine.WaitUntilNotBusy(engine);
            }
            //RunScriptAsCode(controllable);

			Application.Run(view);
            
		}

        static void controllable_StatusUpdate(object sender, string message)
        {
            Console.WriteLine(message);
        }

        private static void engine_StatusUpdate(object sender, string message)
        {
            Console.WriteLine(message);
        }

        static void view_IssueCommand(object sender, DigitalOutCommandEventArgs e)
        {
            if (e.Value)
                controllable[e.Command].On();
            else
                controllable[e.Command].Off();
        }


        static void view_RequestBattery(object sender, EventArgs e)
        {
            ((Controller)controllable).RequestBattery();
        }


        static ScriptEngine RunLines(string scriptPath, IControllable controllable)
        {
            var engine = new ScriptEngine(scriptPath);
            engine.StatusUpdate += engine_StatusUpdate;
            engine.Run(controllable);
            return engine;
        }




        public static void RunScriptAsCode(IControllable controllable)
        {
            var script = new TestScript();
            script.Run(controllable);
        }


	}
}
